/************************************************
 * Author       :   XXY
 * Blog         :   https://www.cnblogs.com/jzyl
 * Gitee        :   https://gitee.com/xiaobaichong
 * Email        :   1047185209@QQ.com
 * FileName     :   MessageNoticeCanvas.cs
 * CreateData   :   2023/9/2 16:58:17
 * UnityVersion :   2021.3.20f1c1
 * Description  :   消息 公告
************************************************/

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;

namespace Main.Framework
{
    public class MessageNoticeCanvas : MonoBehaviour
    {
        [Header("组件")]
        [SerializeField] GameObject noticeWindow;
        [SerializeField] RectTransform mask;
        [SerializeField] TextMeshProUGUI tmp;
        [Header("控制")]
        [SerializeField, Range(0.1f, 5)] float waitTime = 0.5f;  // 等待下个滑动的时间
        [SerializeField, Range(0.1f, 10)] float speed = 2;      // 播放速度


        Queue<string> messages = new Queue<string>();

#pragma warning disable UNT0006 // Incorrect message signature
        private IEnumerator Start()
#pragma warning restore UNT0006 // Incorrect message signature
        {
            while (true)
            {
                yield return null;
                if (messages.Count > 0)
                {
                    noticeWindow.SetActive(true);
                    string msg = messages.Dequeue();
                    yield return StartCoroutine(AnimationTxT(msg));
                }
                else
                {
                    noticeWindow.SetActive(false);
                }
                if (messages.Count > 0)
                {
                    yield return new WaitForSeconds(waitTime);
                }
            }
        }
        private IEnumerator AnimationTxT(string msg)
        {
            RectTransform tmpRect = tmp.GetComponent<RectTransform>();
            tmpRect.anchoredPosition = Vector2.zero;
            tmp.text = msg;
            yield return null;
            yield return null;
            float endX = (mask.rect.width + tmpRect.rect.width) * -1;
            while (tmpRect && tmpRect.anchoredPosition.x > endX)
            {
                tmpRect.anchoredPosition = Vector2.right * (tmpRect.anchoredPosition.x - Time.deltaTime * speed * 50);
                yield return null;
            }
        }
        /// <summary>
        /// 添加到公告队列
        /// </summary>
        /// <param name="msg"></param>
        public void AddMsg(string msg)
        {
            messages.Enqueue(msg.Replace("\n", ""));
        }
    }
}
